Tailwind CSS offers two main approaches to add background images.
Tailwind includes a set of utility classes prefixed with bg- that represent a few built-in background images like gradients. While these classes offer a quick solution, they might not always provide the specific image you need.
<div class="hero bg-gradient-to-r from-purple-500 to-pink-500">
This is a hero section with a gradient background.
</div>
This method provides more flexibility for provinding your own images:
You can use square brackets [ ] to set a custom background image URL directly within a class.
<div class="bg-[url('/path/image.jpg')]">
This element has a custom background image.
</div>
Note: Replace /path/image.jpg with the actual path to your image file.
For more maintainability and reusability, consider adding your image paths to the Tailwind configuration file (tailwind.config.js). Then, create a class referencing the image name.
// tailwind.config.js
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {
backgroundImage: theme => ({
'hero-pattern': "url('/image/hero-img-patt.jpg')",
}),
},
},
plugins: [],
};
<div class="bg-hero-pattern">
This element uses a background image defined in the Tailwind config.
</div>